<template>
  <div class="drawer-content-wrapper">
    <!-- 关联合同区块 -->
    <div class="form-section" v-if="!isEdit">
      <h3 class="form-section-title">关联合同</h3>
      <div class="form-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号">
              <el-input v-model="contractCode" placeholder="请选择合同" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="　">
              <el-button type="success" @click="openContractSelector">关联合同</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 案件编辑表单 -->
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      @submit.prevent="handleSubmit"
      class="case-edit-form"
    >
      <!-- 基本案情区块 -->
      <div class="form-section">
        <h3 class="form-section-title">基本案情</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <!-- 案件编号独自一行 -->
            <el-col :span="24" v-if="isEdit">
              <el-form-item label="案件编号" prop="case_code">
                <el-input v-model="form.case_code" :disabled="!isEdit" />
              </el-form-item>
            </el-col>

            <!-- 隐藏的合同ID字段 -->
            <el-col :span="24" v-if="!isEdit">
              <el-form-item label="合同ID" prop="contract_id" style="display: none">
                <el-input v-model="form.contract_id" type="hidden" />
              </el-form-item>
            </el-col>

            <!-- 案件类型和案由放同一行 -->
            <el-col :span="12">
              <el-form-item label="案件类型" prop="case_type">
                <el-select
                  v-model="form.case_type"
                  placeholder="请选择案件类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(type, index) in CASE_TYPE_OPTIONS"
                    :key="index"
                    :label="type"
                    :value="type"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="案由" prop="case_cause_id">
                <el-select
                  v-model="form.case_cause_id"
                  placeholder="请输入案由关键词搜索"
                  filterable
                  remote
                  :remote-method="remoteSearchCaseCauses"
                  :loading="caseCauseLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="cause in caseCauseOptions"
                    :key="cause.id"
                    :label="cause.name_with_indent"
                    :value="cause.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 管辖法院 -->
            <el-col :span="12">
              <el-form-item label="管辖法院" prop="court_id">
                <el-select
                  v-model="form.court_id"
                  placeholder="请选择管辖法院"
                  style="width: 100%"
                  filterable
                  allow-create
                  @blur="handleCourtBlur('main', $event)"
                >
                  <el-option
                    v-for="court in courtOptions"
                    :key="court.id"
                    :label="court.name"
                    :value="court.id"
                  />
                  <template #empty>
                    <div style="padding: 10px; text-align: center">
                      <span>没有找到匹配的法院</span>
                      <el-button
                        type="text"
                        size="small"
                        @click="openAddCourt('main')"
                        style="margin-left: 10px"
                      >
                        新增法院
                      </el-button>
                    </div>
                  </template>
                </el-select>
                <el-button
                  type="text"
                  size="small"
                  @click="openAddCourt('main')"
                  style="margin-top: 5px"
                >
                  <el-icon><Plus /></el-icon>
                  新增法院
                </el-button>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="当前进度" prop="status">
                <el-select v-model="form.status" placeholder="请选择当前进度" style="width: 100%">
                  <el-option
                    v-for="(status, index) in CASE_STATUS_OPTIONS"
                    :key="index"
                    :label="status"
                    :value="status"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 案件描述 -->
            <el-col :span="24">
              <el-form-item label="案件描述" prop="description">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入案件描述"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 代理信息区块 -->
      <div class="form-section">
        <h3 class="form-section-title">代理信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <!-- 接案日期和代理阶段放同一行 -->
            <el-col :span="12">
              <el-form-item label="接案日期" prop="entrust_date">
                <el-date-picker
                  v-model="form.entrust_date"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择接案日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="代理阶段" prop="stage">
                <el-checkbox-group v-model="selectedStages" class="stage-group">
                  <div class="stage-group-container">
                    <div class="stage-group-section" v-if="filteredStages.length > 0">
                      <el-checkbox
                        v-for="stage in filteredStages"
                        :key="stage.value"
                        :label="stage.value"
                        class="stage-checkbox"
                      >
                        {{ stage.label }}
                      </el-checkbox>
                    </div>
                    <div v-else class="stage-group-section">
                      <span class="text-gray-500">暂无可用阶段选项</span>
                    </div>
                  </div>
                </el-checkbox-group>
              </el-form-item>
            </el-col>

            <!-- 主办律师和管家放同一行 -->
            <el-col :span="12">
              <el-form-item label="主办律师" prop="main_lawyer">
                <el-select
                  v-model="form.main_lawyer"
                  placeholder="请选择主办律师"
                  style="width: 100%"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="lawyer in lawyerOptions"
                    :key="lawyer.lawyer_id"
                    :label="lawyer.lawyer_name"
                    :value="lawyer.lawyer_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="管家" prop="manager">
                <el-select
                  v-model="form.manager"
                  placeholder="请输入管家名称搜索"
                  filterable
                  remote
                  :remote-method="remoteSearchManagers"
                  :loading="managerLoading"
                  style="width: 100%"
                  :popper-append-to-body="false"
                  clearable
                >
                  <!-- 自定义选项模板 -->

                  <el-option
                    v-for="manager in managerOptions"
                    :key="manager.id"
                    :label="manager.name"
                    :value="manager.id"
                  >
                    <span>{{ manager.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 开庭信息区块 -->
      <div class="form-section">
        <h3 class="form-section-title">开庭信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <!-- 开庭处所 -->
            <el-col :span="12">
              <el-form-item label="开庭处所" prop="court_session_place">
                <el-select
                  v-model="form.court_session_place"
                  placeholder="请选择开庭处所"
                  style="width: 100%"
                  filterable
                  allow-create
                  @blur="handleCourtBlur('session', $event)"
                >
                  <el-option
                    v-for="court in courtOptions"
                    :key="court.id"
                    :label="court.name"
                    :value="court.id"
                  />
                  <template #empty>
                    <div style="padding: 10px; text-align: center">
                      <span>没有找到匹配的法院</span>
                      <el-button
                        type="text"
                        size="small"
                        @click="openAddCourt('session')"
                        style="margin-left: 10px"
                      >
                        新增法院
                      </el-button>
                    </div>
                  </template>
                </el-select>
                <el-button
                  type="text"
                  size="small"
                  @click="openAddCourt('session')"
                  style="margin-top: 5px"
                >
                  <el-icon><Plus /></el-icon>
                  新增法院
                </el-button>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="开庭时间" prop="session_time">
                <el-date-picker
                  v-model="form.session_time"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="请选择开庭时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <!-- 出庭律师 -->
            <el-col :span="12">
              <el-form-item label="出庭律师" prop="session_lawyer">
                <el-select
                  v-model="form.session_lawyer"
                  placeholder="请选择出庭律师"
                  style="width: 100%"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="lawyer in lawyerOptions"
                    :key="lawyer.lawyer_id"
                    :label="lawyer.lawyer_name"
                    :value="lawyer.lawyer_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
  </div>

  <!-- 合同选择器弹窗 -->
  <ContractSelectorDialog v-model="contractSelectorVisible" @select="handleContractSelect" />

  <!-- 新增法院弹窗 -->
  <AddCourtDialog
    v-model="addCourtVisible"
    :initial-name="courtNameToAdd"
    @success="handleAddCourtSuccess"
  />
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown, Search, Plus } from '@element-plus/icons-vue'
  import request from '@/utils/request'
  import ContractSelectorDialog from './ContractSelectorDialog.vue'
  import AddCourtDialog from './AddCourtDialog.vue'
  import { CASE_STATUS } from '../../../constants/lawcase'
  import { useLawcaseStore } from '../../../store/lawcase'

  // 在setup函数中
  const CASE_STATUS_OPTIONS = CASE_STATUS

  const CASE_TYPE_OPTIONS = ['民事', '刑事', '行政', '非诉']

  const STAGE_OPTIONS = [
    { label: '其他', value: '其他', group: '其他' },
    { label: '（民）一审阶段', value: '（民）一审阶段', group: '民事' },
    { label: '（民）二审阶段', value: '（民）二审阶段', group: '民事' },
    { label: '（民）调解阶段', value: '（民）调解阶段', group: '民事' },
    { label: '（民）执行阶段', value: '（民）执行阶段', group: '民事' },
    { label: '（刑）一审阶段', value: '（刑）一审阶段', group: '刑事' },
    { label: '（刑）二审阶段', value: '（刑）二审阶段', group: '刑事' },
    { label: '（刑）再审阶段', value: '（刑）再审阶段', group: '刑事' },
    { label: '（行）一审阶段', value: '（行）一审阶段', group: '行政' },
    { label: '（行）二审阶段', value: '（行）二审阶段', group: '行政' },
    { label: '（行）再审阶段', value: '（行）再审阶段', group: '行政' },
  ]

  const civilStages = STAGE_OPTIONS.filter(stage => stage.group === '民事')
  const criminalStages = STAGE_OPTIONS.filter(stage => stage.group === '刑事')
  const administrativeStages = STAGE_OPTIONS.filter(stage => stage.group === '行政')
  const otherStages = STAGE_OPTIONS.filter(stage => stage.group === '其他')

  // 根据案件类型过滤显示的阶段选项
  const filteredStages = computed(() => {
    switch (form.case_type) {
      case '民事':
        return civilStages
      case '刑事':
        return criminalStages
      case '行政':
        return administrativeStages
      case '非诉':
        return otherStages
      default:
        return STAGE_OPTIONS
    }
  })

  interface CaseForm {
    id?: number
    case_code: string
    case_cause_id?: number | null // 最终选择的案由ID
    court_id: number | null
    court_name?: string
    main_lawyer: number | null
    entrust_date: string
    status: string
    case_type: string
    stage: string
    manager: number | null
    description: string
    session_time: string
    session_court_id: number | null
    court_session_place: number | null
    contract_id: number | null
    session_lawyer: number | null
  }

  interface Lawyer {
    id: number
    lawyer_id: number
    lawyer_name: string
  }

  interface CaseCause {
    id: number
    name: string
    parent_id?: number
    level?: number
    children?: CaseCause[]
    name_with_indent?: string
  }

  interface Court {
    id: number
    name: string
  }

  interface Department {
    id: number
    title: string
    pid: number
    children?: Department[]
  }

  interface Employee {
    id: number
    name: string
    did: number
  }

  const props = defineProps<{
    visible: boolean
    isEdit: boolean
    caseData?: any
  }>()

  const emit = defineEmits<{
    (e: 'update:visible', visible: boolean): void
    (e: 'success'): void
  }>()

  const formRef = ref()
  const form = reactive<CaseForm>({
    case_code: '',
    case_cause_id: null,
    court_id: null,
    court_name: '',
    main_lawyer: null,
    entrust_date: new Date().toISOString().split('T')[0], // 默认接案日期为今天
    status: '准备阶段（未提交立案）', // 默认案件状态为准备阶段
    case_type: '民事', // 默认案件类型为民事
    stage: '',
    manager: null,
    description: '',
    session_time: '',
    session_court_id: null,
    court_session_place: null,
    contract_id: null, // 关联合同ID
    session_lawyer: null,
  })

  // 用于复选框绑定的临时数组
  const selectedStages = ref<string[]>([])

  // 合同编号用于显示
  const contractCode = ref('')
  const selectedContractId = ref<number | null>(null)
  const contractSelectorVisible = ref(false)

  // 新增法院相关
  const addCourtVisible = ref(false)
  const courtTypeToAdd = ref<'main' | 'session'>('main')
  const courtNameToAdd = ref('')

  // 案由选择相关
  const caseCauseLoading = ref(false)

  // 管家选择相关
  const managerLoading = ref(false)

  const rules = {
    case_code: [{ required: false }], // 取消案件编号的必填验证
    case_cause_id: [{ required: true, message: '请选择案由', trigger: 'change' }],
    court_id: [{ required: false }],
    main_lawyer: [{ required: false }],
    entrust_date: [{ required: true, message: '请选择接案日期', trigger: 'change' }],
    status: [{ required: true, message: '请选择案件状态', trigger: 'change' }],
    case_type: [{ required: true, message: '请选择案件类型', trigger: 'change' }],
    stage: [{ required: true, message: '请至少选择一个代理阶段', trigger: 'change' }],
  }

  const lawyerOptions = ref<Lawyer[]>([])
  const caseCauseOptions = ref<CaseCause[]>([])
  const courtOptions = ref<Court[]>([])
  const managerOptions = ref<Employee[]>([])

  // 远程搜索案由
  const remoteSearchCaseCauses = async (query: string) => {
    if (query.trim() === '') {
      caseCauseOptions.value = []
      return
    }

    caseCauseLoading.value = true

    try {
      const lawcaseStore = useLawcaseStore()
      const response: any = await lawcaseStore.searchCaseCausesAction(query.trim())
      if (response && response.code === 0) {
        caseCauseOptions.value = response.data || []
      } else {
        caseCauseOptions.value = []
        console.error('搜索案由失败:', response?.msg)
      }
    } catch (error) {
      caseCauseOptions.value = []
      console.error('搜索案由失败:', error)
    } finally {
      caseCauseLoading.value = false
    }
  }

  // 获取律师列表
  const loadLawyerOptions = async () => {
    try {
      const res: any = await request({
        url: '/api/lawcase/cases/get_all_lawyers',
        method: 'get',
        params: {
          page: 1,
          limit: 100,
        },
      })

      if (res.code === 0 && res.data) {
        lawyerOptions.value = res.data
      }
    } catch (error) {
      console.error('获取律师列表失败:', error)
      ElMessage.error('获取律师列表失败')
    }
  }

  // 获取法院列表
  const loadCourtOptions = async () => {
    try {
      const res: any = await request({
        url: '/api/lawcase/courts/set',
        method: 'get',
      })

      if (res.code === 0 && res.data) {
        courtOptions.value = res.data
      }
    } catch (error) {
      console.error('获取法院列表失败:', error)
      ElMessage.error('获取法院列表失败')
    }
  }

  // 打开新增法院对话框
  const openAddCourt = (type: 'main' | 'session') => {
    courtTypeToAdd.value = type
    courtNameToAdd.value = ''
    addCourtVisible.value = true
  }

  // 处理新增法院成功
  const handleAddCourtSuccess = (newCourt: any) => {
    // 重新加载法院列表
    loadCourtOptions()

    // 自动选择新添加的法院
    if (courtTypeToAdd.value === 'main') {
      form.court_id = newCourt.id
    } else {
      form.court_session_place = newCourt.id
    }

    ElMessage.success('法院添加成功')
  }

  // 处理输入框失去焦点事件
  const handleCourtBlur = (type: 'main' | 'session', event: FocusEvent) => {
    const target = event.target as HTMLInputElement
    const inputValue = target.value?.trim()

    if (inputValue && !courtOptions.value.some(court => court.name === inputValue)) {
      // 如果输入了新的法院名称，提示是否新增
      ElMessageBox.confirm(`是否将 "${inputValue}" 添加为新法院？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          // 打开新增法院对话框，预填名称
          courtTypeToAdd.value = type
          courtNameToAdd.value = inputValue
          addCourtVisible.value = true
        })
        .catch(() => {
          // 取消，清空输入
          target.value = ''
        })
    }
  }

  // 根据ID获取管家信息
  const loadManagerInfoById = async (managerId: number) => {
    try {
      // 使用缓存机制搜索管家
      const response: any = await request({
        url: '/api/user/user/search',
        method: 'get',
        params: { keyword: '' },
      })

      if (response && response.code === 0) {
        const managers = response.data || []
        // 查找指定ID的管家
        const manager = managers.find((m: any) => m.id === managerId)
        if (manager) {
          // 检查当前管家是否已在选项中
          const existingManagerIndex = managerOptions.value.findIndex(m => m.id === managerId)
          if (existingManagerIndex === -1) {
            // 将管家添加到选项中，确保选择器能正确显示
            managerOptions.value.unshift(manager)
          } else {
            // 如果管家已存在，更新管家信息（特别是名称）
            managerOptions.value[existingManagerIndex] = {
              ...managerOptions.value[existingManagerIndex],
              ...manager,
            }
            // 触发响应式更新，确保视图能正确显示
            managerOptions.value = [...managerOptions.value]
          }
        }
      } else {
        console.error('获取管家信息失败:', response?.msg)
      }
    } catch (error) {
      console.error('获取管家信息失败:', error)
    }
  }

  // 获取当前选中的管家名称
  const getCurrentManagerName = () => {
    if (form.manager && managerOptions.value) {
      const manager = managerOptions.value.find(m => m.id === form.manager)
      return manager ? manager.name : ''
    }
    return ''
  }

  // 远程搜索管家
  const remoteSearchManagers = async (query: string) => {
    if (query.trim() === '') {
      managerOptions.value = []
      return
    }

    managerLoading.value = true

    try {
      // 使用缓存机制搜索管家
      const response: any = await request({
        url: '/api/user/user/search',
        method: 'get',
        params: { keyword: query.trim() },
      })

      if (response && response.code === 0) {
        managerOptions.value = response.data || []
      } else {
        managerOptions.value = []
        console.error('搜索管家失败:', response?.msg)
      }
    } catch (error) {
      managerOptions.value = []
      console.error('搜索管家失败:', error)
    } finally {
      managerLoading.value = false
    }
  }

  // 打开合同选择器
  const openContractSelector = () => {
    contractSelectorVisible.value = true
  }

  // 处理合同选择
  const handleContractSelect = (contract: any) => {
    // 设置合同ID到隐藏域
    selectedContractId.value = contract.id
    // 设置合同编号到显示输入框
    contractCode.value = contract.code
    ElMessage.success(`已选择合同：${contract.name}`)
  }

  // 从合同导入信息（已废弃，保留用于兼容性）
  const importFromContract = async () => {
    ElMessage.warning('请使用"关联合同"按钮选择合同')
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          let res: any
          if (props.isEdit) {
            // 编辑案件 - 使用正确的API端点，参考Lawcase.vue中的实现
            // 处理主办律师、管家和出庭律师的清空逻辑
            const submitData = {
              ...form,
              id: props.caseData?.id, // 确保传递案件ID
            }

            // 如果主办律师被清空，确保传递0值
            if (form.main_lawyer === null || form.main_lawyer === undefined) {
              submitData.main_lawyer = 0
            }

            // 如果管家被清空，确保传递0值
            if (form.manager === null || form.manager === undefined) {
              submitData.manager = 0
            }

            // 如果出庭律师被清空，确保传递0值
            if (form.session_lawyer === null || form.session_lawyer === undefined) {
              submitData.session_lawyer = 0
            }

            res = await request({
              url: '/api/lawcase/cases/edit',
              method: 'put',
              data: submitData,
            })
          } else {
            // 新增案件 - 排除case_code字段，让后端自动生成唯一编号
            const { case_code, ...formDataWithoutCode } = form
            res = await request({
              url: '/api/lawcase/cases/add',
              method: 'post',
              data: {
                ...formDataWithoutCode,
                contract_id: selectedContractId.value, // 添加关联合同ID
              },
            })
          }

          if (res.code === 0) {
            ElMessage.success(props.isEdit ? '编辑成功' : '新增成功')
            emit('success')
            handleClose()
          } else {
            ElMessage.error(res.msg || (props.isEdit ? '编辑失败' : '新增失败'))
          }
        } catch (error) {
          console.error('操作失败:', error)
          ElMessage.error(props.isEdit ? '编辑失败' : '新增失败')
        }
      }
    })
  }

  // 关闭对话框
  const handleClose = () => {
    emit('update:visible', false)
  }

  // 组件挂载时初始化数据
  onMounted(() => {
    // 编辑模式下的初始数据设置移到watch中处理
  })

  // 监听案件数据变化
  watch(
    () => props.caseData,
    newVal => {
      if (newVal && props.isEdit) {
        // 处理数据初始化
        Object.assign(form, newVal)

        // 确保主办律师和法院字段正确初始化
        form.main_lawyer = newVal.main_lawyer || null
        form.court_id = newVal.court_id || null
        form.case_cause_id = newVal.case_cause_id || null
        form.case_type = newVal.case_type || ''
        // 不再直接从newVal设置stage，而是通过selectedStages处理
        form.status = newVal.status || ''
        form.manager = newVal.manager || null
        form.description = newVal.description || ''
        form.session_time = newVal.session_time || ''
        // 修复：优先使用session_court_id，没有时再使用court_session_place
        form.court_session_place = newVal.session_court_id || newVal.court_session_place || null
      } else {
        // 重置表单
        Object.keys(form).forEach(key => {
          if (key !== 'case_code') {
            ;(form as any)[key] =
              key === 'case_cause_id' ||
              key === 'main_lawyer' ||
              key === 'court_id' ||
              key === 'manager' ||
              key === 'court_session_place'
                ? null
                : ''
          }
        })
      }
    }
  )

  // 监听对话框显示状态变化
  watch(
    () => props.visible,
    newVal => {
      if (newVal) {
        nextTick(async () => {
          // 优先加载选项数据，确保在设置表单值之前选项列表已加载完成
          await Promise.all([loadLawyerOptions(), loadCourtOptions()])

          if (props.isEdit && props.caseData) {
            // 编辑模式：填充表单数据
            Object.keys(form).forEach(key => {
              // 不处理stage字段，让selectedStages来处理
              if (key !== 'stage' && key in props.caseData) {
                ;(form as any)[key] = props.caseData[key]
              }
            })
            // 处理代理阶段数据转换
            if (props.caseData.stage) {
              // 确保正确处理逗号分隔的字符串
              selectedStages.value = props.caseData.stage
                .split(',')
                .map((s: string) => s.trim())
                .filter(Boolean)
            } else {
              selectedStages.value = []
            }
            // 注意：不要在这里直接设置form.stage，让watch(selectedStages)来处理

            // 处理合同关联
            if (props.caseData.contract_id) {
              selectedContractId.value = props.caseData.contract_id
              // 获取合同编号用于显示
              loadContractCode(props.caseData.contract_id)
            }

            // 处理案由显示：如果有案由ID，需要获取案由名称并添加到选项中
            if (props.caseData.case_cause_id && props.caseData.case_cause_name) {
              // 检查当前案由是否已在选项中
              const existingCause = caseCauseOptions.value.find(
                cause => cause.id === props.caseData.case_cause_id
              )
              if (!existingCause) {
                // 将当前案由添加到选项中，确保选择器能正确显示
                caseCauseOptions.value.unshift({
                  id: props.caseData.case_cause_id,
                  name: props.caseData.case_cause_name,
                  name_with_indent: props.caseData.case_cause_name,
                })
              }
            }

            // 处理管家显示：如果有管家ID，需要预先加载管家信息并添加到选项中
            if (props.caseData.manager) {
              // 创建管家对象，使用传入的manager_name或默认名称
              const managerName = props.caseData.manager_name || `管家${props.caseData.manager}`

              // 创建一个完整的管家对象
              const managerObj = {
                id: props.caseData.manager,
                name: managerName,
                did: 0, // 部门ID设为默认值
              }

              // 直接清空并重新设置managerOptions数组，确保只有当前管家在选项中
              managerOptions.value = [managerObj]

              // 先将form.manager设置为null，然后再设置为实际值，强制触发更新
              form.manager = null

              // 使用setTimeout确保DOM更新后再设置实际值
              setTimeout(() => {
                // 使用一个全新的数组引用，确保Vue能够检测到变化
                managerOptions.value = [
                  {
                    id: props.caseData.manager,
                    name: managerName,
                    did: 0,
                  },
                ]

                // 设置表单绑定值
                form.manager = props.caseData.manager
              }, 0)

              // 异步加载管家的完整信息（不影响初始显示）
              setTimeout(() => {
                loadManagerInfoById(props.caseData.manager)
              }, 100)
            }

            // 确保开庭法院和开庭时间字段正确设置
            // 修复：优先使用session_court_id，没有时再使用court_session_place
            const sessionCourtId =
              props.caseData.session_court_id || props.caseData.court_session_place
            if (sessionCourtId) {
              // 使用setTimeout确保DOM更新后再设置开庭法院值
              setTimeout(() => {
                form.court_session_place = sessionCourtId
              }, 0)
            }

            if (props.caseData.session_time) {
              // 确保session_time格式正确，能够被el-date-picker识别
              try {
                let sessionTime = props.caseData.session_time
                let timestamp = null

                // 处理整数时间戳
                if (typeof sessionTime === 'number' && Number.isInteger(sessionTime)) {
                  // 检查是否为毫秒级时间戳（长度为13位）
                  if (sessionTime.toString().length === 13) {
                    // 已经是毫秒级时间戳，直接使用
                    timestamp = sessionTime
                  } else {
                    // 可能是秒级时间戳，转换为毫秒级
                    timestamp = sessionTime * 1000
                  }
                } else if (typeof sessionTime === 'string') {
                  // 检查是否为数字字符串形式的时间戳
                  if (/^\d+$/.test(sessionTime)) {
                    const numTime = parseInt(sessionTime, 10)
                    if (sessionTime.length === 13) {
                      timestamp = numTime
                    } else {
                      timestamp = numTime * 1000
                    }
                  } else {
                    // 检查是否只有日期没有时间(YYYY-MM-DD格式)
                    const dateOnlyRegex = /^\d{4}-\d{2}-\d{2}$/
                    if (dateOnlyRegex.test(sessionTime)) {
                      // 如果只有日期没有时间，添加默认时间" 00:00"
                      sessionTime = sessionTime + ' 00:00'
                    }
                  }
                }

                // 优先使用时间戳创建Date对象
                const date = timestamp !== null ? new Date(timestamp) : new Date(sessionTime)
                // 检查是否为有效日期
                if (!isNaN(date.getTime())) {
                  // 格式化为YYYY-MM-DD HH:mm格式
                  const year = date.getFullYear()
                  const month = String(date.getMonth() + 1).padStart(2, '0')
                  const day = String(date.getDate()).padStart(2, '0')
                  const hours = String(date.getHours()).padStart(2, '0')
                  const minutes = String(date.getMinutes()).padStart(2, '0')
                  form.session_time = `${year}-${month}-${day} ${hours}:${minutes}`
                } else {
                  // 如果不是有效日期，但已经是字符串格式，直接使用
                  form.session_time = props.caseData.session_time
                }
              } catch (error) {
                console.error('格式化开庭时间失败:', error)
                form.session_time = props.caseData.session_time
              }
            }
          } else {
            // 新增模式：重置表单，设置默认值
            Object.keys(form).forEach(key => {
              if (key !== 'case_code') {
                // 不重置案件编号字段
                switch (key) {
                  case 'status':
                    ;(form as any)[key] = '准备阶段（未提交立案）' // 默认案件状态为准备阶段
                    break
                  case 'case_type':
                    ;(form as any)[key] = '民事' // 默认案件类型为民事
                    break
                  case 'entrust_date':
                    ;(form as any)[key] = new Date().toISOString().split('T')[0] // 默认接案日期为今天
                    break
                  default:
                    ;(form as any)[key] = typeof (form as any)[key] === 'string' ? '' : null
                }
              }
            })
            selectedStages.value = [] // 清空代理阶段选择
            selectedContractId.value = null
            contractCode.value = ''
          }
          // 重新加载选项数据
          loadLawyerOptions()
          loadCourtOptions()
        })
      }
    },
    { immediate: true }
  )

  // 监听代理阶段选择变化，同步到form.stage
  watch(selectedStages, newVal => {
    form.stage = newVal.join(',')
  })

  // 监听案件类型变化，清空已选阶段
  watch(
    () => form.case_type,
    (newType, oldType) => {
      if (newType !== oldType) {
        selectedStages.value = []
      }
    }
  )

  // 根据合同ID加载合同编号
  const loadContractCode = async (contractId: number) => {
    try {
      const res: any = await request({
        url: '/api/contract/contract/view',
        method: 'get',
        params: { id: contractId },
      })
      if (res.code === 0 && res.data) {
        contractCode.value = res.data.code
      }
    } catch (error) {
      console.error('获取合同编号失败:', error)
    }
  }

  // 暴露方法给父组件调用
  defineExpose({
    handleSubmit,
  })
</script>

<style scoped>
  /* 使用全局drawer-content-wrapper样式，保持一致性 */
  .case-edit-form {
    padding: 0;
  }

  .form-section {
    margin-bottom: 30px;
    position: relative;
  }

  .form-section::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 4px;
    height: 22px;
    background-color: #67c23a;
    border-radius: 2px;
  }

  .form-section-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 10px;
    padding-left: 15px;
    border-bottom: 1px solid #ebeef5;
    position: relative;
  }

  .form-container {
    background-color: #fafafa;
    padding: 20px;
    border-radius: 6px;
    margin-bottom: 20px;
  }

  /* 表单项间距优化 */
  .el-form-item {
    margin-bottom: 18px;
  }

  /* 输入框样式统一 */
  .el-input,
  .el-select,
  .el-date-picker {
    width: 100%;
  }

  /* 必填项的样式 */
  .el-form-item.is-required .el-form-item__label::before {
    color: #f56c6c;
  }

  /* 代理阶段复选框分组 */
  .stage-group {
    width: 100%;
  }

  .stage-group-container {
    width: 100%;
  }

  .stage-group-section {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
  }

  .stage-checkbox {
    margin: 0;
    white-space: nowrap;
  }

  .stage-checkbox :deep(.el-checkbox__label) {
    font-size: 14px;
    padding-left: 6px;
  }

  .text-gray-500 {
    color: #909399;
    font-size: 14px;
  }
</style>
